package com.tensquare.user.controller;

import com.tensquare.user.pojo.Admin;
import com.tensquare.user.service.AdminService;
import com.tensquare.user.service.UserService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;

    @GetMapping("/sendsms/{mobile}")
    public Result sendSms(@PathVariable String mobile) {
        userService.sendSms(mobile);
        return new Result(true, StatusCode.OK, "发送成功");
    }

    @PostMapping("/login")
    public Result login(@RequestBody Admin admin) {
        Admin adminlogin = adminService.login(admin);
        if(adminlogin==null){
            return new Result(false,StatusCode.OK,"登录失败");
        }
        //使前后通话的操作.JWT
        //生成令牌
        String token = jwtUtil.createJWT(adminlogin.getId(), adminlogin.getLoginname(), "admin");
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("role","admin");
        return new Result(true,StatusCode.OK,"登录成功",map);


    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable String id){
        adminService.delete(id);
        return new Result(true,StatusCode.OK,"登录成功");
    }

    @PostMapping("/user")
    public Result save(@RequestBody Admin admin){
        adminService.add(admin);
        return new Result(true,StatusCode.OK,"保存成功");

    }
}
